package com.fjwt.gz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjwt.gz.core.interfaces.UserAssetService;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.db.entity.AssetQuarterEntity;
import com.fjwt.gz.db.entity.FansEntity;
import com.fjwt.gz.db.vo.AssetQuarterVO;
import com.fjwt.gz.service.mapper.AssetQuarterMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户季度资产等级表 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class AssetQuarterService extends ServiceImpl<AssetQuarterMapper, AssetQuarterEntity> {

    @Value("${province.code}")
    private String provinceCode;
    @Autowired
    FansService fansService;
//    @Autowired
//    private ScoreRecordService scoreRecordService;

    private static final int PAGE_SIZE = 1000; // 每页数据量
    /**
     * 处理单个用户季度资产等级数据
     */
    public Map<String, Integer> quarterAssetLevel(Long fansId, String cstmNo,String agentNo) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 计算当前年份和季度
        int year = currentDate.getYear();
        int quarter = (currentDate.getMonthValue() - 1) / 3 + 1;
        if (!agentNo.equals("41000122")&&!agentNo.equals("22011060")){
            Map<String,Integer> map = new HashMap<>();
            map.put("year",year);
            map.put("quarter",quarter);
            map.put("inSearch",2);
            return map;
        }

        // 计算上一个季度
        int previousQuarter = quarter - 1;
        int previousYear = year;
        if (previousQuarter == 0) {
            previousQuarter = 4;
            previousYear = year - 1;
        }

        log.info("用户季度资产等级查询的年月:{}，{}", previousYear, previousQuarter);
        AssetQuarterEntity assetLevelQuarterEntiy = this.selectQuarter(fansId, previousYear, previousQuarter, agentNo);
        log.info("季度资产等级查询数据:{}", assetLevelQuarterEntiy);
        Map<String,Integer> map = new HashMap<>();
        if (assetLevelQuarterEntiy == null){
            //查询资产等级接口
            UserAssetService userAssetService = SpringBeansUtil.getBean(provinceCode + "UserAssetService", UserAssetService.class);
            Integer userAssetLevel = userAssetService.quarterUserAssetLevel(cstmNo,previousYear,previousQuarter);
            log.info("用户{}，季度资产等级实时查询数据:{}", fansId, userAssetLevel);

            //如果上个月没查出来，则进行上上个月的查询
            if (userAssetLevel == null) {

                // 计算上一个季度
                previousQuarter = previousQuarter - 1;
                if (previousQuarter == 0) {
                    previousQuarter = 4;
                    previousYear = year - 1;
                }

                log.info("用户资产等级二次查询的年月:{}，{}", previousYear, previousQuarter);
                Map<String,Integer> map1 = new HashMap<>();
                assetLevelQuarterEntiy = this.selectQuarter(fansId, previousYear, previousQuarter, agentNo);
                if (assetLevelQuarterEntiy == null){
                    userAssetLevel = userAssetService.quarterUserAssetLevel(cstmNo,previousYear, previousQuarter);
                    if (userAssetLevel == null){

                        map1.put("year",previousYear);
                        map1.put("quarter",previousQuarter);
                        map1.put("inSearch",1);
                        log.info("用户暂查询异常{}，资产等级二次查询数据:{}", fansId, userAssetLevel);
                        return map1;
                    }else {
                        map.put("userAssetLevel",userAssetLevel);
                        map1.put("year",previousYear);
                        map1.put("quarter",previousQuarter);
                        map1.put("inSearch",1);
                        log.info("用户{}暂无上月数据，资产等级二次查询数据:{}", fansId, userAssetLevel);
                        return map1;
                    }
                }
                map1.put("userAssetLevel",assetLevelQuarterEntiy.getLevel());
                map1.put("year",previousYear);
                map1.put("quarter",previousQuarter);
                map1.put("inSearch",1);
                log.info("用户{}暂无上月数据，资产等级二次查询数据:{}", fansId, userAssetLevel);
                return map1;
            }


//          写入数据库
            AssetQuarterEntity assetLevel = new AssetQuarterEntity();
            assetLevel.setFansId(fansId);
            assetLevel.setYear(previousYear);
            assetLevel.setQuarter(previousQuarter);
            assetLevel.setLevel(userAssetLevel);
            assetLevel.setAgentNo(agentNo);
            assetLevel.setCreatedAt(DateUtil.date());
            log.info("用户季度资产等级写入数据库的数据:{}", assetLevel);
            save(assetLevel);

            map.put("userAssetLevel",userAssetLevel);
            map.put("year",previousYear);
            map.put("quarter",previousQuarter);
            map.put("inSearch",0);
            log.info("用户季度资产等级写入数据库的数据:{}", map);

            return map;

        }else {
            map.put("userAssetLevel",assetLevelQuarterEntiy.getLevel());
            map.put("year",previousYear);
            map.put("quarter",previousQuarter);
            map.put("inSearch",0);
            return map;
        }

    }


    //季度资产等级查询
    public AssetQuarterEntity selectQuarter(Long fansId, int year, int quarter, String agentNo) {
        // 是否已拉取资产等级
        LambdaQueryWrapper<AssetQuarterEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AssetQuarterEntity::getFansId, fansId);
        queryWrapper.eq(AssetQuarterEntity::getYear, year);
        queryWrapper.eq(AssetQuarterEntity::getQuarter, quarter);
        queryWrapper.eq(AssetQuarterEntity::getAgentNo, agentNo);
        AssetQuarterEntity assetLevelQuarterEntiy = getOne(queryWrapper);
        return assetLevelQuarterEntiy;
    }

    /**
     * 处理数据库中的用户资产等级数据
     */
    public void processQuarter() {
        int page = 1;
        ExecutorService executorService = Executors.newFixedThreadPool(10); // 创建线程池

        while (true) {
//            List<FansEntity> assetLevelEntities = fansService.getAssetLevelsByPage(page, PAGE_SIZE);
            List<FansEntity> assetLevelEntities = null;
            if (assetLevelEntities.isEmpty()) {
                break;
            }
            // todo 柴云浩改为查询用户实名信息
            for (FansEntity assetLevelEntity : assetLevelEntities) {
//                if (!JSONUtil.isNull(assetLevelEntity)&&!JSONUtil.isNull(assetLevelEntity.getIsAuth())){
//                    if(assetLevelEntity.getIsAuth() == 1||JSONUtil.isNull(assetLevelEntity.getAuthTime())||JSONUtil.isNull(assetLevelEntity.getCstmNo())){
//                        log.info("用户未实名");
//                        continue;
//                    }
//                }else {
//                    log.info("用户实名信息异常");
//                    continue;
//                }
                executorService.submit(() -> processQuarter(assetLevelEntity));
            }
            page++;
        }

        executorService.shutdown();
        try {
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        log.info("用户季度资产等级数据处理完成");
    }

    /**
     * 处理单个用户资产等级数据
     */
    private void processQuarter(FansEntity assetLevelEntity) {

        Long fansId = assetLevelEntity.getFansId();
        // todo 柴云浩改为fansAuth
//        String cstmNo = assetLevelEntity.getCstmNo();
        String cstmNo = null;

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 计算当前年份和季度
        int year = currentDate.getYear();
        int quarter = (currentDate.getMonthValue() - 1) / 3 + 1;

        // 计算上一个季度
        int previousQuarter = quarter - 1;
        int previousYear = year;
        if (previousQuarter == 0) {
            previousQuarter = 4;
            previousYear = year - 1;
        }


        UserAssetService userAssetService = SpringBeansUtil.getBean(provinceCode + "UserAssetService", UserAssetService.class);
        if (cstmNo == null){
            throw new RuntimeException("用户编号不能为空");
        }
        Integer userAssetLevel = userAssetService.quarterUserAssetLevel(cstmNo,previousYear,previousQuarter);

        log.info("用户季度资产等级:{}", userAssetLevel);
        if (userAssetLevel != null) {
            AssetQuarterEntity assetLevel = new AssetQuarterEntity();
            assetLevel.setFansId(fansId);
            assetLevel.setYear(previousYear);
            assetLevel.setQuarter(previousQuarter);
            assetLevel.setLevel(userAssetLevel);
            assetLevel.setCreatedAt(DateUtil.date());
            log.info("用户季度资产等级写入数据库的数据:{}", assetLevel);
            save(assetLevel);

        }
        if (userAssetLevel == null){
            throw new RuntimeException("用户季度资产等级查询失败");
        }
    }

    public IPage<AssetQuarterVO> selectQuarterList(IPage iPage, Long fansId, String locationAgentNo) {
        // 是否已拉取资产等级
        LambdaQueryWrapper<AssetQuarterEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AssetQuarterEntity::getFansId, fansId);
        queryWrapper.orderByDesc(AssetQuarterEntity::getCreatedAt);
        queryWrapper.eq(AssetQuarterEntity::getAgentNo, locationAgentNo);
        IPage<AssetQuarterEntity> assetQuarterEntityList = page(iPage, queryWrapper);
        //转换
        List<AssetQuarterVO> voList = assetQuarterEntityList.getRecords().stream().map(entity -> {
            AssetQuarterVO vo = BeanUtil.copyProperties(entity, AssetQuarterVO.class);
            return vo;
        }).collect(Collectors.toList());
        //封装
        IPage<AssetQuarterVO> pageVo = new Page<>();
        pageVo.setRecords(voList);
        pageVo.setTotal(assetQuarterEntityList.getTotal());
        pageVo.setCurrent(assetQuarterEntityList.getCurrent());
        pageVo.setSize(assetQuarterEntityList.getSize());
        return pageVo;
    }


}
